#include <QAction>
#include <QToolBar>
#include "http-database-client.h"
#include "http-database-client-store.h"
#include "graph-node.h"
#include "icon-store.h"
#include "model-helper.h"
#include "section-graph-creator.h"
#include "section-info.h"
#include "server-section-model.h"
#include "server-section-view.h"
#include "table-view.h"
#include "value-result.h"

ServerSectionView::ServerSectionView(QWidget *parent) :
    StandardSectionView(parent)
{
}

void ServerSectionView::initialize()
{
    m_addDataText = "Dodaj serwer";
    m_editDataText = "Edytuj serwer";
    m_removeDataText = "Usuń serwer";
    m_removeDataConfirmation = "Czy na pewno chcesz usunąć zaznaczone serwery?";
    m_sectionModel = new ServerSectionModel(this);
    setDescendantViewEnabled(false);
    setDatabaseClientEnabled(false);
    StandardSectionView::initialize();

    QAction* connectToServerAction = new QAction(IconStore::icon(IconStore::StatusRunning, m_toolBarIconSize),
                                                 "Połącz z serwerem", this);
    connect (connectToServerAction, &QAction::triggered, this, &ServerSectionView::connectToServer);
    m_toolBar->addAction(connectToServerAction);
}

void ServerSectionView::connectToServer()
{
    QModelIndexList indexes = ModelHelper::selectedIndexes(m_tableView);
    if (indexes.isEmpty())
        return;

    m_databaseClient = HttpDatabaseClientStore::databaseClient(indexes.at(ServerSectionModel::AddressColumn).data().toString(),
                       indexes.at(ServerSectionModel::PortColumn).data().toInt());
    ValueResult* result = m_databaseClient->connectToDatabase();
    connect (result, &ValueResult::resultReady, this, &ServerSectionView::connectionReady);
}

void ServerSectionView::connectionReady (ValueResult* result)
{
    result->deleteLater();
    if (result->hasError())
    {
        emit notifyWarning("Błąd połączenia", result->error().text());
        m_databaseClient.clear();
        return;
    }

    if (!m_sectionNode->hasChildNodes()
        || m_sectionNode->childNodes().at(0)->data().databaseClient() != m_databaseClient)
    {
        SectionGraphCreator graphCreator;
        graphCreator.createDatabaseGraph(m_sectionNode, m_databaseClient);
    }

    emit showSectionRequested (m_sectionNode->childNodes().at(0), false);
}

void ServerSectionView::tableViewItemActivated (const QModelIndex& index)
{
    Q_UNUSED(index);
    if (!m_sectionModel->isEditingEnabled())
        connectToServer();
}
